package cn.zh.controller;

import cn.hutool.captcha.LineCaptcha;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *
 * 验证码请求
 */
@RestController
public class CaptchaController {

    //生成验证码
    @RequestMapping(value = "captcha",method = RequestMethod.GET)
    public void createCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //生成验证码图片,保存验证码
        LineCaptcha lineCaptcha = new LineCaptcha(100,40,4,4);
        String code = lineCaptcha.getCode();
        System.out.println("code = " + code);
        //session -> cookie     request     application -> code:xxxx
        HttpSession session = request.getSession();
        session.setAttribute("code",code);

        //将图片以流的形式写到前端
        ServletOutputStream outputStream = response.getOutputStream();
        lineCaptcha.write(outputStream);
        outputStream.close();
    }
}
